package com.yc.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yc.pay.api.req.NetBankPayReq;
import com.yc.pay.api.resp.NetBankPayData;
import com.yc.pay.api.resp.RespVo;
import com.yc.pay.factory.PayWayFactory;
import com.yc.pay.model.MchInfo;
import com.yc.pay.model.MchPayWay;
import com.yc.pay.model.PaySerial;

import com.yc.pay.service.IMchPayWayService;
import com.yc.pay.service.IMchService;
import com.yc.pay.service.IPaySerialService;
import com.yc.pay.service.InetBankPayService;
import com.yc.pay.service.strategy.IStrategyPay;
//import com.yc.pay.utils.AlipayUtils;
import com.yc.pay.utils.PayDigestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 网银支付接口实现类
 */
@Service
public class NetBankPayServiceImpl implements InetBankPayService {

    @Autowired
    private IMchService mchService;

    @Autowired
    private IMchPayWayService mchPayWayService;

    @Autowired
    private IPaySerialService paySerialService;

//    @Autowired
//    private AlipayUtils alipayUtils;

    private static final Logger logger = LoggerFactory.getLogger(NetBankPayServiceImpl.class);


    /**
     *  网银支付
     * @param netBankPayReq
     * @return
     */
    @Override
    public RespVo<NetBankPayData> netBankPay(NetBankPayReq netBankPayReq) throws InterruptedException {

        //判断商户id是否存在，是否可用
        MchInfo mchInfo = mchService.queryByMchId(netBankPayReq.getMchId());
        if (ObjectUtils.isEmpty(mchInfo) || "1".equals(mchInfo.getStatus())){
            logger.info("订单号：{}商户id不存在或状态不可用",netBankPayReq.getOrderNo());
            return RespVo.returnFailRespVo("商户id不存在或状态不可用");
        }

        //判断支付方式是否可用
       MchPayWay mchPayWay = mchPayWayService.queryByMchIdAndPayWay(netBankPayReq.getMchId(),netBankPayReq.getPayWay());
        if (ObjectUtils.isEmpty(mchPayWay) || "1".equals(mchPayWay.getStatus())){
            logger.info("订单号：{}商户支付方式不存在，或支付状态不可用",netBankPayReq.getOrderNo());

            return RespVo.returnFailRespVo("商户支付方式不存在，或支付状态不可用");
        }

        //签名验证，
        String sign = netBankPayReq.getSign();

        //再次生成签名。
        JSONObject jsonObject = (JSONObject)JSON.toJSON(netBankPayReq);
        jsonObject.remove("sign");

        String newSign = PayDigestUtil.getSign(jsonObject,mchInfo.getReqKey());

        if (!sign.equals(newSign)){
            logger.info("订单号：{}请求非法",netBankPayReq.getOrderNo());

            return RespVo.returnFailRespVo("请求非法");
        }

        //生成流水，

        PaySerial paySerial = null;
        try{
            //线程2 ，3，5o....
            JedisServiceImpl.tryGetDistributedLock(null,null,null,10);

            //线程1:15s
            paySerial = paySerialService.createPaySerial(netBankPayReq);
        }finally {
            JedisServiceImpl.releaseDistributedLock(null,null,null);
        }


        if (ObjectUtils.isEmpty(paySerial)){
            logger.info("订单号：{}商户订单已经存在符合条件的流水",netBankPayReq.getOrderNo());
            return RespVo.returnFailRespVo("商户订单已经存在符合条件的流水");
        }

        //调用支付接口

        IStrategyPay iStrategyPay = PayWayFactory.getPay(netBankPayReq.getPayWay());
        if(ObjectUtils.isEmpty(iStrategyPay)){
            logger.info("订单号：{}没有找到对应的支付策略",netBankPayReq.getOrderNo());
            return RespVo.returnFailRespVo("没有找到对应的支付策略");
        }

        RespVo respVo = iStrategyPay.pay();


//        if(PayWayEnums.ALIPAY_QRCODE_PAY.getCode().equals(netBankPayReq.getPayWay())){
//
//            RespVo<NetBankPayData>  respVo = alipayUtils.qrCodePay(netBankPayReq.getSubject(),paySerial.getPaySerialNo(),netBankPayReq.getAmount());
//
//            NetBankPayData netBankPayData = respVo.getData();
//            BeanUtils.copyProperties(netBankPayReq,netBankPayData);
//
//            //生成返回参数签名
//            String respKey = mchInfo.getRespKey();
//
//            //对象转Jsonobject
//
//            JSONObject dataMap = (JSONObject)JSON.toJSON(netBankPayData);
//            dataMap.remove("sign");
//
//            String respSign = PayDigestUtil.getSign(dataMap,respKey);
//            netBankPayData.setSign(respSign);
//
//            return RespVo.returnSuccessRespVo(netBankPayData);
//
//        } else if(PayWayEnums.ALIPAY_WAP_PAY.getCode().equals(netBankPayReq.getPayWay())){
//
//            RespVo<NetBankPayData>  respVo = alipayUtils.wapPay(netBankPayReq.getSubject(),paySerial.getPaySerialNo(),netBankPayReq.getAmount(),
//                    netBankPayReq.getQuitUrl(),netBankPayReq.getReturnUrl());
//
//
//        } else if(PayWayEnums.WECHAT_QRCODE_PAY.getCode().equals(netBankPayReq.getPayWay())){
//
//        }

        //封装对象返回

        return respVo;
    }
}
